import { Button, Input, InputNumber, message, Modal, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { FC, forwardRef, Ref, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { getFactorule } from './data';
interface Props {
  innerRef: Ref<{ showModal: (params: any) => void } | undefined>;
  id?: string; //因子id
  type: number; //1车辆相关，2司机相关，3驾驶行为
  onChange?: (list: any) => void;
}

type RuleTableProps = {
  id?: string;
};
type RTRef = {
  onSave: () => void;
  //   onSave: () => Promise<any>;
};
const RuleTable = forwardRef<RTRef, RuleTableProps>(({ id }, ref) => {
  const [listData, setListData] = useState<any[]>([]);
  //新增
  const addRow = () => {
    const newRow = {
      name: '',
      num: '',
    };

    setListData((v) => {
      console.log([...v, newRow]);
      return [...v, newRow];
    });
  };

  //删除
  const del = (index: any) => {
    listData.splice(index, 1);
    setListData(listData.slice());
  };

  //校验
  const verification = () => {
    let flag = true;
    if (listData.length) {
      flag = listData.every((item) => {
        if (!item.name) {
          message.error('细则不能为空');
          return false;
        }
        if (!String(item.num)) {
          message.error('得分不能为空');
          return false;
        }
        return true;
      });
      if (!flag) {
        return;
      }
    }
    return flag;
  };

  //保存
  const onSave = () => {
    if (!verification()) {
      console.log('不通过', listData);
      return false;
    }
    return listData;
    // console.log('提交的listData', listData);
    // updateAssessmentLevelGroup({ entId: entId, gradeRequests: listData }).then(() => {
    //   message.open({
    //     type: 'success',
    //     content: '保存成功',
    //   });
    //   updataList();
  };

  useImperativeHandle(ref, () => ({
    onSave,
  }));

  const columns: ColumnsType<any> = [
    {
      title: '细则',
      dataIndex: 'name',
      key: 'name',
      render(value, record, index) {
        return (
          <Input
            placeholder="请输入"
            maxLength={20}
            value={record.name}
            onChange={(e) => {
              const list = listData;
              list[index].name = e.target.value;
              setListData(list.slice());
            }}
          ></Input>
        );
      },
      width: '140px',
    },
    {
      title: '得分',
      dataIndex: 'num',
      key: 'num',
      width: '100px',
      render(value, record, index) {
        return (
          <InputNumber
            min={1}
            max={9999}
            precision={0}
            placeholder="请输入"
            defaultValue={record.num}
            onChange={(e) => {
              setListData((v) => {
                v[index].num = e;
                return [...v];
              });
            }}
          />
        );
      },
    },
    {
      title: (
        <Button type="text" size="small" onClick={() => addRow()}>
          <span className="safe-edu_table_operation_text">新增</span>
        </Button>
      ),
      dataIndex: 'opr',
      key: 'opr',
      fixed: 'right',
      width: '80px',
      render(value, record, index) {
        return (
          <>
            {index != 0 ? (
              <Button type="text" size="small" onClick={() => del(index)}>
                <span className="safe-edu_table_operation_text">删除</span>
              </Button>
            ) : (
              ''
            )}
          </>
        );
      },
    },
  ];

  const updataList = () => {
    //获取这个因子设置的规则
    getFactorule().then((data) => {
      setListData(data);
    });
  };

  useEffect(() => {
    if (id) {
      console.log('取到因子id：', id);
      updataList();
    } else {
      addRow();
    }
  }, [id]);

  return (
    <Table
      style={{ minHeight: '216px', maxHeight: 'calc(100vh - 260px)', overflow: 'auto' }}
      sticky
      dataSource={listData}
      columns={columns}
      pagination={false}
      rowKey="sort"
    />
  );
});

export const RuleSetModal: FC<Props> = ({ innerRef, onChange, id, type }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const ruleDataList = useRef<RTRef>(null);
  /*
   *打开弹窗
   */
  const showModal = (row: any) => {
    setIsOpen(true);
  };

  //提交表单
  const handleOk = async () => {
    const params = ruleDataList.current?.onSave();
    if (params) {
      console.log('请求params,', params);
      onChange && onChange(params);
      setConfirmLoading(false);
      setIsOpen(false);
    }
  };

  //初始化
  useEffect(() => {
    setConfirmLoading(false);
  }, [isOpen]);

  useImperativeHandle(innerRef, () => ({ showModal: showModal }));

  return (
    <Modal
      getContainer={false}
      className="ruleSet-model"
      title="规则设置"
      maskClosable={false}
      open={isOpen}
      onOk={handleOk}
      onCancel={() => setIsOpen(false)}
      width={480}
      centered
      okText="确定"
      destroyOnClose={true}
      confirmLoading={confirmLoading}
      cancelButtonProps={{ type: 'cancel' as any }}
    >
      <RuleTable ref={ruleDataList} id={id}></RuleTable>
    </Modal>
  );
};
